package com.leyou.trade.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.auth.utils.UserContext;
import com.leyou.common.exceptions.LyException;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.SkuDTO;
import com.leyou.trade.dto.OrderFormDTO;
import com.leyou.trade.entity.Order;
import com.leyou.trade.entity.OrderDetail;
import com.leyou.trade.entity.OrderLogistics;
import com.leyou.trade.entity.enums.OrderStatus;
import com.leyou.trade.mapper.OrderMapper;
import com.leyou.trade.service.OrderDetailService;
import com.leyou.trade.service.OrderLogisticsService;
import com.leyou.trade.service.OrderService;
import com.leyou.trade.utils.PayHelper;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.AddressDTO;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private OrderDetailService detailService;

    @Autowired
    private UserClient userClient;

    @Autowired
    private OrderLogisticsService logisticsService;

    @Autowired
    private PayHelper payHelper;

    //创建订单
    @Override
    @Transactional
    public Long createOrder(OrderFormDTO orderFormDTO) {
        //1.处理order数据
        Order order = new Order();
        //1.1 处理订单金额相关数据，查询sku，根据sku价格计算总金额，根据物流算运费、根据商品算优惠、计算实付金额

        Map<Long, Integer> carts = orderFormDTO.getCarts();
        //获取sku的id集合
        Set<Long> skuIds = carts.keySet();
        List<SkuDTO> skuDTOList = itemClient.querySkuByIds(skuIds);
        //遍历，计算总金额
        long total = 0;
        for (SkuDTO skuDTO : skuDTOList) {
            //判断商品状态
            if (!skuDTO.getSaleable()){
                //商品下架
                throw new LyException(400,"商品已经下架，无法下单");
            }
            //获取商品购买数量
            Integer num = carts.get(skuDTO.getId());
            total += skuDTO.getPrice() * num;
        }

        order.setTotalFee(total);
        //TODO 根据物流算运费，目前全场包邮
        order.setPostFee(0L);
        //TODO 根据商品算优惠，目前没有优惠
        order.setActualFee(total+order.getPostFee());
        order.setPaymentType(orderFormDTO.getPaymentType());

        //1.2 用户信息
        Long userId = UserContext.getUser().getId();
        order.setUserId(userId);

        //1.3 默认状态
        order.setStatus(OrderStatus.INIT.getValue());

        //1.4 写入数据库
        boolean success = this.save(order);
        if (!success){
            throw new LyException(500,"订单新增失败！");
        }

        //1.5 订单id 回显(雪花算法生成)
        Long orderId = order.getOrderId();


        //2.处理orderDetail
        List<OrderDetail> details = new ArrayList<>(skuDTOList.size());
        //2.1.将每一个sku，转为一个OrderDetail
        for (SkuDTO skuDTO : skuDTOList) {
            OrderDetail detail = new OrderDetail();
            details.add(detail);
            detail.setTitle(skuDTO.getTitle());
            detail.setSpec(skuDTO.getSpecialSpec());
            detail.setSkuId(skuDTO.getId());
            detail.setPrice(skuDTO.getPrice());
            detail.setOrderId(orderId);
            detail.setNum(carts.get(skuDTO.getId()));
            detail.setImage(StringUtils.substringBefore(skuDTO.getImages(),","));
        }
        //2.2.写入数据库
        detailService.saveBatch(details);


        //3.处理orderLogistics
        Long addressId = orderFormDTO.getAddressId();
        // 3.1.先根据id查询地址信息
        AddressDTO addressDTO = userClient.queryAddressById(addressId);
        // 3.2.查询的地址信息封装到OrderLogistics
        OrderLogistics orderLogistics = addressDTO.toEntity(OrderLogistics.class);
        orderLogistics.setOrderId(orderId);
        // 3.3.写入数据库
        success = logisticsService.save(orderLogistics);
        if (!success){
            throw new LyException(500,"订单新增失败！");
        }
        //4.减库存
        try {
            itemClient.deductStock(carts);
        } catch (FeignException e) {
            throw new LyException(e.status(),e.contentUTF8());
        }
        return orderId;
    }

    //获取支付链接
    @Override
    public String getPayUrl(Long orderId) {
        //1.查询订单
        Order order = this.getById(orderId);
        //2.判断订单是否存在
        if (order == null) {
            throw new LyException(400,"订单编号不存在");
        }
        //3.判断订单状态是否是未付款
        Integer status = order.getStatus();
        if (!Objects.equals(status, OrderStatus.INIT.getValue())){
            // 订单已经关闭或者已经支付，无需再次获取支付链接
            throw new LyException(400,"订单已经支付或关闭");
        }
        //4.生成支付链接
        Long actualFee = order.getActualFee();
        String payUrl = payHelper.getPayUrl(orderId, actualFee);
        return payUrl;
    }

    //处理微信支付回调
    @Override
    public void handleWxNotify(Map<String, String> data) {
        // 1.校验通信标示
        payHelper.checkReturnCode(data);
        // 2.校验业务标示
        payHelper.checkResultCode(data);
        // 3.校验签名
        payHelper.isSignatureValid(data);
        // 4.订单金额校验
        // 4.1.获取结果中的订单id和支付金额
        String outTradeNo = data.get("out_trade_no");
        String totalFee = data.get("total_fee");
        // 4.2.校验数据是否为空
        if (StringUtils.isBlank(outTradeNo) || StringUtils.isBlank(totalFee)){
            throw new LyException(400,"通知参数有误！");
        }
        // 4.3.查询数据库订单金额
        Long orderId = null;
        try {
            orderId = Long.valueOf(outTradeNo);
        } catch (NumberFormatException e) {
            throw new LyException(400,"通知参数有误！");
        }
        Order order = this.getById(orderId);
        if (order == null){
            // 订单id是错误的
            throw new LyException(400,"订单id错误");
        }
        // 4.4.校验订单金额
        Long actualFee = order.getActualFee();
        if (!StringUtils.equals(actualFee.toString(),totalFee)){
            // 订单金额不匹配
            throw new LyException(400,"订单金额错误");
        }
        // 5.业务幂等校验(判断订单状态）
        if (!Objects.equals(order.getStatus(), OrderStatus.INIT.getValue())){
            // 订单已经支付或者关闭，是重复通知，无需处理
            return;
        }
        // 6.修改订单状态从未支付到已支付
        // update tb_order set status = 2, pay_time = NOW() where order_id = 110 AND status = 1
        //AND status = 1 乐观锁  解决线程安全问题
        this.update()
                .set("status",OrderStatus.PAY_UP.getValue())
                .set("pay_time",new Date())
                .eq("order_id",orderId)
                .eq("status",OrderStatus.INIT.getValue())
                .update();
        log.info("接收并处理了微信回调通知，更新订单状态成功！订单id：{}", orderId);
    }

    //根据id查询订单状态(支付成功后查询订单状态跳转支付成功页面)
    @Override
    public Integer queryOrderStatus(Long orderId) {
        // 1.查询订单
        Order order = this.getById(orderId);
        if (order == null) {
            //订单不存在
            throw new LyException(400, "订单不存在！");
        }
        // 2.返回状态
        return order.getStatus();
    }
}